<?php
include_once(dirname(__FILE__) .'/abstract.php');
class Mysql extends DbAbstract {
	/**
	数据库架构查询结果返回格式: 
	1(返回的每一个记录就是一个索引数组) 
	2(返回的每一个记录就是一个以字段名作为键名的数组) 
	**/
	protected $fetch_mode_assoc = 2;

	/** 指示是否将查询结果中的字段名转换为全小写 **/
	public $result_field_name_lower = false;

	/** 查询句柄 **/
	protected $_handle = null;

	function __construct($dsn, $id=null)
    {
        if (! is_array($dsn)) {
            $dsn = DB::parseDSN($dsn);
        }
        parent::__construct($dsn, $id);
        $this->_schema = $dsn['database'];
    }

	/** 内容安全过滤 **/
	function saftCheck($names, $as = null)
	{
		return parent::safeFilter($names, $as);
	}

	function connect($pconnect = false, $force_new = false)
	{
        if (is_resource($this->_conn)) { return; }

       if (isset($this->_dsn['port']) && $this->_dsn['port'] != '') {
            $host = $this->_dsn['host'] . ':' . $this->_dsn['port'];
        } else {
            $host = $this->_dsn['host'];
        }
        if (! isset($this->_dsn['login'])) {
            $this->_dsn['login'] = '';
        }
        if (! isset($this->_dsn['password'])) {
            $this->_dsn['password'] = '';
        }

        if ($pconnect) {
            $this->_conn = mysql_pconnect($host, $this->_dsn['login'], $this->_dsn['password'], $force_new);
        } else {
            $this->_conn = mysql_connect($host, $this->_dsn['login'], $this->_dsn['password'], $force_new);
        }

        if (! is_resource($this->_conn)) {
            //throw new QDB_Exception('CONNECT DATABASE', mysql_error(), mysql_errno());
			exit("CONNECT DATABASE Exception");
        }

        if (! empty($this->_dsn['database'])) {
            $this->execute('USE ' . $this->saftCheck($this->_dsn['database']));
        }

        if (isset($this->_dsn['charset']) && $this->_dsn['charset'] != '') {
            $charset = $this->_dsn['charset'];
            $this->execute("SET NAMES '" . $charset . "'");
        }
    }

    function pconnect()
    {
        $this->connect(true);
    }

    function nconnect()
    {
        $this->connect(false, true);
    }

    function close()
    {
        if (is_resource($this->_conn)) {
            mysql_close($this->_conn);
        }
        parent::_clear();
    }

	function dropSeq($seq_name)
    {
        $this->execute(sprintf('DROP TABLE %s', $this->saftCheck($seq_name)));
    }

	function nextID($table_name, $field_name, $start_value = 1)
    {
	}

    function insertID()
    {
        return mysql_insert_id($this->_conn);
    }

    function affectedRows()
    {
        return mysql_affected_rows($this->_conn);
    }

	function execute($sql, $inputarr = null)
	{
        if (! $this->_conn) {
            $this->connect();
        }
        $result = mysql_query($sql, $this->_conn);

        if (is_resource($result)) {
            return $this->resultMysql($result, $this->fetch_mode_assoc);
        } elseif ($result) {
            return $result;
        } else {
            $this->_last_err = mysql_error($this->_conn);
            $this->_last_err_code = mysql_errno($this->_conn);
            $this->_has_failed_query = true;

            if ($this->_last_err_code == 1062) {
                //throw new QDB_Exception_DuplicateKey($sql, $this->_last_err, $this->_last_err_code);
				exit("QUERY Exception 1062 : " .  $this->_last_err);
            } else {
                //throw new QDB_Exception($sql, $this->_last_err, $this->_last_err_code);
				exit("QUERY Exception : " .  $this->_last_err);
            }
        }
    }

    function selectLimit($sql, $offset = 0, $length = 30, array $inputarr = null)
    {
		 if (! is_null($offset)) {
            $sql .= ' LIMIT ' . (int) $offset;

            if (! is_null($length)) {
                $sql .= ', ' . (int) $length;
            } else {
                $sql .= ', 18446744073709551615';
            }
        } elseif (! is_null($length)) {
            $sql .= ' LIMIT ' . (int) $length;
        }
        return $this->execute($sql, $inputarr);
	}

	/** 处理执行结果：返回对象  **/
	function resultMysql($handle, $fetch_mode=2)
	{
		if (is_resource($handle) || is_object($handle)) {
			$this->_handle = $handle;
			$array['_handle'] = $handle;
		}
		$this->fetch_mode = $fetch_mode;
		$array['fetch_mode'] = $fetch_mode;

		$obj = (object) $array; //转换为对象
		return $obj;
	}

	/** 取一列数据 **/
	function fetchRow()
	{
		if ($this->fetch_mode == $this->fetch_mode_assoc) {
			$row = mysql_fetch_assoc($this->_handle);
			if ($this->result_field_name_lower && $row) {
				return array_change_key_case($row, CASE_LOWER);
			} else {
				return $row;
			}
		} else {
			return mysql_fetch_array($this->_handle);
		}
	}




	/**
	 * (功能描述) 从查询句柄提取一条记录，并返回该记录的第一个字段
	 *
	 * @param 
	 * @return
	 */
	function fetchOne()
	{
		$row = $this->fetchRow();
		return $row ? reset($row) : null;
	}

	/**
	 * (功能描述) 从查询句柄中提取记录集
	 *
	 * @return array
	 */
	function fetchAll()
	{
		$rowset = array();
		while (($row = $this->fetchRow())) {
			$rowset[] = $row;
		}
		return $rowset;
	}


}